package com.qf.controller;

;
import com.qf.bean.User;

import com.qf.constant.SSMConstant;
import com.qf.service.UserService;
import com.yunpian.sdk.YunpianClient;
import com.yunpian.sdk.model.Result;
import com.yunpian.sdk.model.SmsSingleSend;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController {

    private  final String CODE = "usercode";
    private final String REGISTER_PAGE = "user/register";
    private final String LOGIN_PAGE = "user/login";
    @Autowired
    private UserService userService;
    @Value("${apikey}")
    private String apikey;

    //发送的后继手机短信
    @RequestMapping("/sendsms")
    @ResponseBody
    public String sendSms(@RequestParam String phone, HttpSession session){
        // 获取6位数验证码
        String code = (int)((Math.random()*9+1)*100000) + "";
        System.out.println(code);
        // 将正确的验证码放到session中
        session.setAttribute(CODE,code);
        //初始化clnt,使用单例方式
        YunpianClient clnt = new YunpianClient(apikey).init();
        //发送短信API
        Map<String, String> param = clnt.newParam(2);
        param.put(YunpianClient.MOBILE, phone);
        param.put(YunpianClient.TEXT, "【云片网】您的验证码是"+code);
        Result<SmsSingleSend> r = clnt.sms().single_send(param);
        //获取返回结果，返回码:r.getCode(),返回码描述:r.getMsg(),API结果:r.getData(),其他说明:r.getDetail(),调用异常:r.getThrowable()
        //账户:clnt.user().* 签名:clnt.sign().* 模版:clnt.tpl().* 短信:clnt.sms().* 语音:clnt.voice().* 流量:clnt.flow().* 隐私通话:clnt.call().*
        //释放clnt
        clnt.close();
        return "短信发送成功";
    }

    //异步校验用户名  http://localhost/user/checkusername
    //接收(响应)json参数（要用Map或者pojo类并且要反序列化）
    /**
     * json的反序列化工具
     * jsonlib   很少用了
     * jackson   spring默认支持jackson
     * gson      spring默认支持gson，但是更推荐jackson
     * fastJSon  号称速度最快的json序列化工具
     */
    @RequestMapping("/checkusername")
    @ResponseBody  //返回的数据不通过视图解析器，直接响应给浏览器
    public Map<String,Object> checkUsername(@RequestBody User user){
        //获取用户名
        String username = user.getUsername();
        //调用service判断是否可用
        Integer count = userService.checkUsername(username);
        //3.响应数据
        Map<String,Object> result = new HashMap<>();
        result.put("data",count);
        return result;
    }

    //跳转到注册页面  ,method = {RequestMethod.POST,RequestMethod.GET}   BindingResult bindingResult 就是接收User类传过来的信息
    @RequestMapping(value = "/register")
    public String register(@Valid User user, BindingResult bindingResult,
                           String registerCode,
                           HttpSession session){
        //1.判断参数
        if(StringUtils.isEmpty(registerCode) || bindingResult.hasErrors()){
            //参数不合法
            return REGISTER_PAGE;
        }
        //2.判断验证码是否正确
        String userCode = (String) session.getAttribute(CODE);
        if(registerCode.equals(userCode)){
          //验证码正确 开始注册功能
           Integer count = userService.register(user);
            if(count == 1){
                //注册成功
                return "redirect:/user/login";
            }
        }
            //验证码不正确   跳转到注册页面
            return REGISTER_PAGE;

    }
    //跳转到登录页面
    @RequestMapping("/login")
    public String login(String username, String password, HttpSession session, Model model){
        //1.判断参数是否合法
        if(StringUtils.isEmpty(username) || StringUtils.isEmpty(password) ){
            //参数不合法
            return LOGIN_PAGE;
        }
        //2.参数合法=执行登录
       User user = userService.login(username,password);
        if(user !=null){
            //登录成功
            session.setAttribute(SSMConstant.USER,user);
            //跳转到商品页面
            return "redirect:/item/list";
        }else {
            //登录失败跳转到登录页面
            //登录失败，给用户提示
            model.addAttribute("loginInfo","用户名或密码错误");
            return LOGIN_PAGE;
        }


    }

}
